import { HeadingPitchRoll, Transforms, WebMapTileServiceImageryProvider } from 'cesium';
import './style.css'
import * as Cesium from 'cesium'
const divContainer = document.getElementById('app') as HTMLDivElement
const viewer = new Cesium.Viewer(divContainer, {
})
// 替换为你申请的天地图 API Key
const tdtKey = "1415bf6128045d22d06a89146a6074d7&SERVICE";


// 天地图影像图层 (卫星图层)
const imageryProvider = new WebMapTileServiceImageryProvider({
  url: `http://t{s}.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&tk=${tdtKey}`,
  layer: "img",
  style: "default",
  format: "tiles",
  tileMatrixSetID: "w",
  maximumLevel: 18,
  subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"],
  tilingScheme: new Cesium.WebMercatorTilingScheme(),
  tileMatrixLabels: [...Array(19).keys()].map(String),  // 矩阵标签（0 到 18）
});

// 将天地图图层添加到 Cesium Viewer 中
viewer.imageryLayers.addImageryProvider(imageryProvider);
// 定义地球的长半轴（单位：米）
const earthSemiMajorAxis = 6378137.0; // 地球长半轴
const circleRadius = 2 * earthSemiMajorAxis; // 圆的半径，2倍地球长半轴

// 生成圆的坐标（位于 y-z 平面，x=0）
const positions: Cesium.Cartesian3[] = [];
const numPoints = 360;
for (let i = 0; i <= numPoints; i++) {
  const angle = Cesium.Math.toRadians(i);
  const x = 0; // 本初子午面，x轴为0
  const y = circleRadius * Math.cos(angle);
  const z = circleRadius * Math.sin(angle);
  positions.push(new Cesium.Cartesian3(x, y, z));
}

// 创建 PolylineGeometry
const trackGeometry = new Cesium.PolylineGeometry({
  positions: positions,
  width: 2.0, // 线宽
  vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
});

// 创建几何实例
const trackInstance = new Cesium.GeometryInstance({
  geometry: trackGeometry,
  attributes: {
    color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.YELLOW),
  },
});

// 添加 Primitive
viewer.scene.primitives.add(new Cesium.Primitive({
  geometryInstances: trackInstance,
  appearance: new Cesium.PolylineColorAppearance({
    translucent: false, // 是否启用透明
  }),
}));

// const origin = new Cesium.Cartesian3(0, 0, circleRadius);
const model = Cesium.Model.fromGltfAsync({
  url: '/Cesium_Air.glb',
  modelMatrix: Cesium.Transforms.eastNorthUpToFixedFrame(positions[0]),
  scale: 200000.0,
})
model.then((model) => {
  viewer.scene.primitives.add(model)
  // 旋转的航向、俯仰和横滚（Heading, Pitch, Roll），设置为绕 Z 轴旋转 90 度
  const hpr = new HeadingPitchRoll(Cesium.Math.toRadians(90), 0, 0); // 90 度航向，俯仰和横滚为 0
  // model.he
  // 生成模型的初始矩阵，应用旋转
  // 在时钟更新事件中更新位置
  let i = 0;
  viewer.clock.onTick.addEventListener(() => {

    i++;
    if (i === positions.length) {
      i = 0
    }
    // const modelMatrix = Transforms.headingPitchRollToFixedFrame(positions[i], hpr);
    model.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(positions[i]);
  });
})